//
//  UrlRequestManager.m
//  LO_MUSIC
//
//  Created by 向祖华 on 16/2/29.
//  Copyright © 2016年 杨少锋. All rights reserved.
//

#import "UrlRequestManager.h"

@implementation UrlRequestManager
//请求方法实现
+(void)requestWith:(requestUrlType)type URL:(NSString*)URL condition:(NSDictionary*)condition SuccesBlock:(successBlock)successBlock faileBlock:(faileBlock)failBlock{
    if (type == GET) {
        //创建请求类的对象
        UrlRequestManager * manager = [[UrlRequestManager alloc] init];
        //调用get请求的方法
        [manager get:URL condition:condition success:successBlock faile:failBlock];
    }else{
        //调用post请求的方法
        UrlRequestManager * manager = [[UrlRequestManager alloc] init];
        [manager post:URL condition:condition success:successBlock faile:failBlock];
    }
}
//GET方法
-(void)get:(NSString*)url condition:(NSDictionary*)condition success:(successBlock)success faile:(faileBlock)faile{
    //创建session（交互）对象
    NSURLSession * session = [NSURLSession sharedSession];
    //拼接url(block内部修改外部的值需要用“__block”修饰)
    __block NSMutableString * urlStr = [NSMutableString stringWithString:url];
    //拼接？
    [urlStr appendString:@"?"];
    //条件拼接
    [condition enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        //拼接
        [urlStr appendString:[NSString stringWithFormat:@"%@=%@&",key,obj]];
        
    }];
    //去掉最后一个&（多拼接了一个&）
    [urlStr substringToIndex:[urlStr length]- 2];
    //转码
    //创建一个集合（包含数字/汉字/字母/符号）
    NSCharacterSet * set = [NSCharacterSet characterSetWithCharactersInString:urlStr];
    //字符串转码UTF-8
    NSString * urlString = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:set];
    //创建请求对象
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    //设置request类型
    [request setHTTPMethod:@"GET"];
    //创建任务
    NSURLSessionTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data&&!error) {
            id item = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
            NSLog(@"item = %@",item);
            if (success) {//如果解析成功，回调出去
                success(item);
                return ;
            }
            else{
                NSLog(@"seccessBlock为空");
                return;
            }
        }
        if (faile) {
            faile(error);
        }
    }];
    //启动请求
    [task resume];

}

//POST
-(void)post:(NSString*)url condition:(NSDictionary*)condition success:(successBlock)success faile:(faileBlock)faile{
    NSURLSession * session = [NSURLSession sharedSession];
    //拼接url
    NSMutableString * urlStr = [NSMutableString stringWithString:url];
    //拼接？
    [urlStr appendString:@"?"];
    //转码
    NSCharacterSet * set = [NSCharacterSet characterSetWithCharactersInString:urlStr];
    //字符串转码UTF-8
    NSString * urlString = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:set];
    //body字符串
    __block NSMutableString * bodyStr = [NSMutableString string];
    
    [condition enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        //拼接
        [bodyStr appendString:[NSString stringWithFormat:@"%@=%@&",key,obj]];
        
    }];
    //去掉最后一个&
    [bodyStr substringToIndex:[urlStr length]- 2];
    
    //创建请求对象
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    //设置request类型
    [request setHTTPMethod:@"POST"];
    //设置body
    NSData * data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    //创建任务
    NSURLSessionTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data&&!error) {
            id item = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
            //            NSLog(@"item = %@",item);
            if (success) {//如果解析成功，回调出去
                success(item);
                return ;
            }
            else{
                NSLog(@"seccessBlock为空");
                return;
            }
        }
        if (faile) {
            faile(error);
        }
    }];
    //
    [task resume];
}
//调用宏定义单例初始化方法
single_implementation(UrlRequestManager);
@end
